package parser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Vector;

public class RaisecomParser implements IParser {

	@Override
	public void parse(String filePath) {
		
		/*格式如：
		 * XinGangOLT#show interface olt 1/1 mac-address-table l2-address
			Count of MAC table: 531
			
			MAC Address     ONU ID   Flags
			------------------------------
			b8f8.2814.61d0  1/1/14   dynamic
			f43e.61c0.5c3f  1/1/14   dynamic
			fc8b.97d4.97d3  1/1/1    dynamic
			0012.d670.4c50  4/1(SNI) dynamic
			0012.d670.521d  4/1(SNI) dynamic
			0012.d670.523f  4/1(SNI) dynamic
		 */
		File file=new File(filePath);
		String olt = file.getName();
		olt = olt.substring(0,olt.indexOf(".log"));
		File file1=new File(filePath+".out");
		try {
			if(!file.exists()||file.isDirectory())
			    throw new FileNotFoundException();
			
			
			FileWriter fw=new FileWriter(file1);
			BufferedReader br=new BufferedReader(new FileReader(file));
			String temp=br.readLine();
			String[] onu;
			int i=0;
			while(temp!=null){	
				if (temp.indexOf("dynamic") >0 && temp.indexOf("SNI") <0) {
					onu = temp.split("\\s+"); //以n个空格切分
					fw.write("id:"+i+",olt:"+olt+",eoc mac:"+onu[0]+",getOnuPort:"+onu[1]+"\n");					
					i++;					
				}	
			    temp=br.readLine();
			}
			br.close();
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("deal "+filePath+" error!" );
		} 
    }	

	/*格式如：
	 * XinGangOLT#show interface olt mac-address-table onu-learning-counter
		ONU ID      MAC Learning Counter
		--------------------------------
		1/1/1       12
		1/1/2       1
		1/1/3       17
		1/1/5       7
	 */
	public Vector<String> preParse(String midData) {
		try{
			BufferedReader br = new BufferedReader(new InputStreamReader(
													new ByteArrayInputStream(midData.getBytes())
												   ));  
			String temp=br.readLine();
			String[] onu;
			String[] ids;
			Vector<String> retv = new Vector();
			
			String reg = "^\\d{1,2}/\\d{1,2}/\\d{1,2}.*";
			while(temp!=null){	
				if (temp.matches(reg)) {
					onu = temp.split("\\s+");
					ids = onu[0].split("/");
					String pon = ids[0]+"/"+ids[1];
					if (!retv.contains(pon)) {
						retv.add(pon);
					}	
				}	
			    temp=br.readLine();			    
			}
			br.close();
			return retv;
		} catch (Exception e) {
			e.printStackTrace();			
		} 	
		return null;
	}
	
	public static void main(String[] args) {
		RaisecomParser p = new RaisecomParser();
//		p.parse("F:/tims/10.2.254.250.log");
		
		String ss = "1/12/12 sfsf\n1/2/2\n1/12/3";
		Vector<String> vs = p.preParse(ss);
		for(int i = 0;i < vs.size();i++){ 
			System.out.println(vs.get(i)); 
		} 
	}

}
